package com.event.management.backend.config;

import com.event.management.backend.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 缓存清除切面
 * 在指定的服务方法执行成功后自动清除缓存
 */
@Aspect
@Component
@Slf4j
public class CacheEvictAspect {
    
    @Autowired
    private CacheUtil cacheUtil;
    
    /**
     * 定义切点：所有service包下的update、save、add、delete、remove开头的方法
     */
    @Pointcut("execution(* com.event.management.backend.service..*.update*(..)) || " +
              "execution(* com.event.management.backend.service..*.save*(..)) || " +
              "execution(* com.event.management.backend.service..*.add*(..)) || " +
              "execution(* com.event.management.backend.service..*.delete*(..)) || " +
              "execution(* com.event.management.backend.service..*.remove*(..))")
    public void cacheEvictPointcut() {
    }
    
    /**
     * 在目标方法执行成功后清除所有缓存
     */
    @AfterReturning("cacheEvictPointcut()")
    public void clearCacheAfterMethodExecution(JoinPoint joinPoint) {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        
        log.info("执行缓存清除: {}#{}", className, methodName);
        
        // 清除所有缓存
        cacheUtil.clearAllCache();
    }
} 